import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.List;

public class TeacherMainFrame extends JFrame {
    private User currentUser;
    private JTable examTable;
    private DefaultTableModel tableModel;
    private JButton createExamButton;
    private JButton editExamButton;
    private JButton deleteExamButton;
    private JButton gradeExamButton;
    private JButton viewStudentsButton;
    private JButton refreshButton;
    private JButton logoutButton;
    private ExamDAO examDAO;

    public TeacherMainFrame(User user) {
        this.currentUser = user;
        this.examDAO = new ExamDAO();
        initComponents();
        setupLayout();
        setupEvents();
        loadExamList();
    }

    private void initComponents() {
        setTitle("在线考试系统 - 教师端 (" + currentUser.getRealName() + ")");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(1200, 800);
        setLocationRelativeTo(null);
        setResizable(true);

        // 表格列名
        String[] columnNames = { "考试ID", "考试名称", "开始时间", "结束时间", "时长(分钟)", "总分", "状态", "参与人数" };
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        examTable = new JTable(tableModel);
        examTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        examTable.setRowHeight(35);
        examTable.setFont(new Font("微软雅黑", Font.PLAIN, 16));

        // 设置表格列宽
        examTable.getColumnModel().getColumn(0).setPreferredWidth(60);
        examTable.getColumnModel().getColumn(1).setPreferredWidth(250);
        examTable.getColumnModel().getColumn(2).setPreferredWidth(150);
        examTable.getColumnModel().getColumn(3).setPreferredWidth(150);
        examTable.getColumnModel().getColumn(4).setPreferredWidth(100);
        examTable.getColumnModel().getColumn(5).setPreferredWidth(80);
        examTable.getColumnModel().getColumn(6).setPreferredWidth(100);
        examTable.getColumnModel().getColumn(7).setPreferredWidth(100);

        // 设置表头
        examTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 16));
        examTable.getTableHeader().setPreferredSize(new Dimension(0, 40));

        // 初始化按钮
        Dimension buttonSize = new Dimension(130, 45);
        Font buttonFont = new Font("微软雅黑", Font.BOLD, 16);

        createExamButton = new JButton("创建考试");
        createExamButton.setPreferredSize(buttonSize);
        createExamButton.setFont(buttonFont);

        editExamButton = new JButton("编辑考试");
        editExamButton.setPreferredSize(buttonSize);
        editExamButton.setFont(buttonFont);

        deleteExamButton = new JButton("删除考试");
        deleteExamButton.setPreferredSize(buttonSize);
        deleteExamButton.setFont(buttonFont);
        deleteExamButton.setBackground(new Color(220, 53, 69));
        deleteExamButton.setForeground(Color.WHITE);

        gradeExamButton = new JButton("阅卷");
        gradeExamButton.setPreferredSize(buttonSize);
        gradeExamButton.setFont(buttonFont);

        viewStudentsButton = new JButton("查看学生");
        viewStudentsButton.setPreferredSize(buttonSize);
        viewStudentsButton.setFont(buttonFont);

        refreshButton = new JButton("刷新");
        refreshButton.setPreferredSize(buttonSize);
        refreshButton.setFont(buttonFont);

        logoutButton = new JButton("退出登录");
        logoutButton.setPreferredSize(buttonSize);
        logoutButton.setFont(buttonFont);
    }

    private void setupLayout() {
        setLayout(new BorderLayout());

        // 顶部面板
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.setBackground(new Color(70, 130, 180));
        topPanel.setPreferredSize(new Dimension(1200, 70));

        JLabel titleLabel = new JLabel("我的考试", JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 26));
        titleLabel.setForeground(Color.WHITE);

        JPanel userPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        userPanel.setBackground(new Color(70, 130, 180));
        JLabel userLabel = new JLabel("欢迎，" + currentUser.getRealName() + " 老师");
        userLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        userLabel.setForeground(Color.WHITE);
        userPanel.add(userLabel);
        userPanel.add(logoutButton);

        topPanel.add(titleLabel, BorderLayout.CENTER);
        topPanel.add(userPanel, BorderLayout.EAST);

        // 中间表格面板
        JScrollPane scrollPane = new JScrollPane(examTable);
        scrollPane.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createEmptyBorder(),
                "考试列表",
                TitledBorder.CENTER,
                TitledBorder.TOP,
                new Font("微软雅黑", Font.BOLD, 18),
                new Color(70, 130, 180)));

        // 底部按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 15));
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0));
        buttonPanel.add(createExamButton);
        buttonPanel.add(editExamButton);
        buttonPanel.add(deleteExamButton);
        buttonPanel.add(gradeExamButton);
        buttonPanel.add(viewStudentsButton);
        buttonPanel.add(refreshButton);

        add(topPanel, BorderLayout.NORTH);
        add(scrollPane, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    private void setupEvents() {
        createExamButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                createExam();
            }
        });

        editExamButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                editExam();
            }
        });

        deleteExamButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                deleteExam();
            }
        });

        gradeExamButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                gradeExam();
            }
        });

        viewStudentsButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                viewStudents();
            }
        });

        refreshButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                loadExamList();
            }
        });

        logoutButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                logout();
            }
        });

        // 双击编辑考试
        examTable.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent e) {
                if (e.getClickCount() == 2) {
                    editExam();
                }
            }
        });
    }

    private void loadExamList() {
        tableModel.setRowCount(0);
        List<Exam> exams = examDAO.getExamsByTeacher(currentUser.getId());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        ExamRecordDAO recordDAO = new ExamRecordDAO();

        for (Exam exam : exams) {
            // 获取参与人数
            List<ExamRecord> records = recordDAO.getExamRecordsByExam(exam.getId());
            int participantCount = records.size();

            Object[] row = {
                    exam.getId(),
                    exam.getTitle(),
                    sdf.format(exam.getStartTime()),
                    sdf.format(exam.getEndTime()),
                    exam.getDuration(),
                    exam.getTotalScore(),
                    getStatusText(exam.getStatus()),
                    participantCount
            };
            tableModel.addRow(row);
        }
    }

    private String getStatusText(String status) {
        switch (status) {
            case "draft":
                return "草稿";
            case "published":
                return "已发布";
            case "finished":
                return "已结束";
            default:
                return status;
        }
    }

    private void createExam() {
        new CreateExamFrame(currentUser, this).setVisible(true);
    }

    private void editExam() {
        int selectedRow = examTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择一个考试！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        int examId = (Integer) tableModel.getValueAt(selectedRow, 0);
        Exam exam = examDAO.getExamById(examId);
        if (exam != null) {
            new CreateExamFrame(currentUser, this, exam).setVisible(true);
        }
    }

    private void deleteExam() {
        int selectedRow = examTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要删除的考试！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        int examId = (Integer) tableModel.getValueAt(selectedRow, 0);
        String examTitle = (String) tableModel.getValueAt(selectedRow, 1);

        // 检查是否有人作答
        if (examDAO.hasExamRecords(examId)) {
            JOptionPane.showMessageDialog(this,
                    "该考试已有学生作答，无法删除！\n\n考试名称：" + examTitle,
                    "删除失败",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 确认删除
        int result = JOptionPane.showConfirmDialog(this,
                "确定要删除考试吗？\n\n考试名称：" + examTitle + "\n\n删除后无法恢复！",
                "确认删除",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.WARNING_MESSAGE);

        if (result == JOptionPane.YES_OPTION) {
            if (examDAO.deleteExam(examId)) {
                JOptionPane.showMessageDialog(this, "考试删除成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                loadExamList(); // 刷新列表
            } else {
                JOptionPane.showMessageDialog(this, "考试删除失败！", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private void gradeExam() {
        int selectedRow = examTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择一个考试！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        int examId = (Integer) tableModel.getValueAt(selectedRow, 0);
        new GradeExamFrame(examId, currentUser).setVisible(true);
    }

    private void viewStudents() {
        int selectedRow = examTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择一个考试！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        int examId = (Integer) tableModel.getValueAt(selectedRow, 0);
        String examTitle = (String) tableModel.getValueAt(selectedRow, 1);
        new ExamStudentListFrame(examId, examTitle, currentUser).setVisible(true);
    }

    private void logout() {
        int result = JOptionPane.showConfirmDialog(this, "确定要退出登录吗？", "确认", JOptionPane.YES_NO_OPTION);
        if (result == JOptionPane.YES_OPTION) {
            new LoginFrame().setVisible(true);
            this.dispose();
        }
    }

    public void refreshExamList() {
        loadExamList();
    }
}